const router = require('koa-router')()
const fs = require('fs')
const jwt = require("jsonwebtoken");

router.get('/images', async ctx => {
  const page = parseInt(ctx.query.page) || 1;
  const pageSize = parseInt(ctx.query.pageSize) || 10;
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  try {
    const files = await fs.promises.readdir(path.resolve(__dirname, 'uploads'));
    const total = files.length;
    const images = files.slice(start, end).map(file => {
      const { name, size, type } = fs.statSync(path.resolve(__dirname, 'uploads', file));
      return { name, size, type };
    });
    ctx.body = { images, total };
  } catch (err) {
    ctx.throw(500, `获取图片列表失败: ${err.message}`);
  }
});
// 上传图片
router.post('/images', async ctx => {
  const file = ctx.request.files.file;
  const name = file.name;
  const oldPath = file.path;
  const newPath = path.resolve(__dirname, 'uploads', name);
  try {
    await fs.promises.rename(oldPath, newPath);
    ctx.status = 201;
  } catch (err) {
    ctx.throw(500, `上传图片失败: ${err.message}`);
  }
});
// 删除图片
router.delete('/images/:name', async ctx => {
  const name = ctx.params.name;
  const filePath = path.resolve(__dirname, 'uploads', name);
  try {
    await fs.promises.unlink(filePath);
    ctx.status = 204;
  } catch (err) {
    ctx.throw(500, `删除图片失败: ${err.message}`);
  }
});

const mykey = "131415"
const token = jwt.sign({
  exp: Math.floor(Date.now() / 1000) + (60 * 60),
  data: 'foobar',
  username:'zhangsan',
  pwd:123456
}, mykey);
console.log(token);

jwt.verify(token, mykey,function(err, decoded) {
  console.log(decoded) // bar
});

// 获取token值
router.get('/api/token', async (ctx) => {
  ctx.body = { token }
})
// 验证token值
router.post('/api/validate', async (ctx) => {
  const { token: clientToken } = ctx.request.body
  if (clientToken === token) {
    ctx.body = { success: true }
  } else {
    ctx.body = { success: false }
  }
})
// 文件上传

router.post('/api/upload', async (ctx) => {
  const { file } = ctx.request.files
  const reader = fs.createReadStream(file.path)
  const stream = fs.createWriteStream(`./uploads/${file.name}`)
  reader.pipe(stream)
  ctx.body = { success: true }
})








router.get("/getInformation", async (ctx, next) => {
  ctx.body = {
    content: {"username":"zhangsan","pwd":"123456"}
  }
})


router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})



module.exports = router
